import fs from 'fs';
import express from 'express';
const app = express();

function set_header(res) {
    res.setHeader('Access-Control-Allow-Origin', '*');
}

app.use('/node_modules', express.static('node_modules'));

app.get('/finder', (req, res) => {
    set_header(res);
    var path = req.query.path;
    if (path.substring(0, 1) !== '/') {
        path = '/' + path;
    }
    if (!path.endsWith('/')) {
        path += '/';
    }
    fs.stat('./root' + path, (err, info) => {
        if (err) {
            res.send('error:文件信息获取失败，错误信息：' + err.toString());
            return;
        }
        if (info.isFile()) {
            res.send('error:这是一个文件，不是文件夹');
            return;
        }
        var dirs = fs.readdirSync('./root' + path);
        var dir_list = [];
        var file_list = [];
        var dir_id = 0;
        var file_id = 0;
        for (var dir in dirs) {
            var d = path + dirs[dir];
            var stat = fs.statSync(`./root${d}`);
            if (stat.isDirectory()) {
                dir_list.push({
                    dir_id: dir_id,
                    filename: d,
                    is_file: false,
                    is_dir: true,
                    selected: ''
                });
                ++dir_id;
            } else if (stat.isFile()) {
                file_list.push({
                    file_id: file_id,
                    filename: d,
                    is_file: true,
                    is_dir: false,
                    selected: ''
                });
                ++file_id;
            } else {
                file_list.push({
                    file_id: file_id,
                    filename: d,
                    is_file: false,
                    is_dir: false,
                    selected: ''
                });
                ++file_id;
            }
        }
        res.send(JSON.stringify({
            dir_list: dir_list,
            file_list: file_list
        }));
    });
});

const port = 80;
app.listen(port, () => {
    console.log(`listen :${port}...`);
});
